<template>
  <scroll-view scroll-y="true"
               style="height: 100%;">
    <block v-for="(item, index) in items">
      <view id="{{item.value.name}}"
            class="scroll-view-item"
            data-index="{{index}}"
      >{{item.value.name}}</view>
    </block>
    <view style="height:60rpx;"></view>
  </scroll-view>
</template>

<script>
async function getItems() {
  let items = [0,1,2,3,4,5,6,7,8,9]
  items = items.map(v => {
    return {
      name: 'name' + v
    }
  })
  return items
}

class ListItem {
  constructor(value) {
    this.value = value
    this.hadReport = false
  }
}

export default {
  behaviors: [],
  data() {
    return {
      items: [],
    }
  },
  attached() {
    console.log(this.$getPage())
  },
  methods: {
    resetObserver() {
      if (this._observer && this._observer.disconnect) {
        this._observer.disconnect()
      }
      this._observer = this.createIntersectionObserver({ observeAll: true })
      this._observer.relativeToViewport({ bottom: 0 })
        .observe('.scroll-view-item', (res) => {
          const { index } = res.dataset;
          let items = this.data.items
          if (!items[index].hadReport) {
            console.log(`report ${index}`)
            items[index].hadReport = true;
            this.setData({
              items: [].concat(items)
            })
          }
        })
    },
    fetchData() {
      let self = this
      getItems().then(items => {
        let _items = items.map(item => {
          return new ListItem(item)
        })
        console.log(_items)
        self.setData({
          items: _items
        }, () => {
          self.resetObserver()
        })
      }).catch(e => { console.error(e) })
    },
  },
}
</script>

<style lang="scss">
</style>
